package com.java2007.hotel.filter;

import com.java2007.hotel.pojo.User;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Reckeys
 * @version V1.0
 * @date 2021/01/11
 **/
public class AuthorizationFilter implements Filter {
    private String[] fNames;


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        //获取初数据
//        String names = "bottom.jsp,left.jsp,right.jsp,top.jsp,index.jsp," +
//                "food-list.jsp,food-save.jsp,food-update.jsp," +
//                "order-detail.jsp,order-list.jsp," +
//                "table-list.jsp,table-save.jsp";
        String names = filterConfig.getInitParameter("ftName");
        fNames = names.split(",");
    }

    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws ServletException, IOException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;


        //判断管理员页面是否已经跳转过一次
        String uri = request.getRequestURI();
        //判断是不是后端页面
        for (String fName : fNames) {
            if (uri.endsWith(fName)){
                //1.判断session是否有用户数据?
                User user = (User) request.getSession().getAttribute("user");
                if(null == user) {
                    //3.没有，不放行。重定向到登录页面
                    response.sendRedirect(request.getContextPath() + "/user/login.jsp");
                    return;
                }else if (user.getUserRole() == 0 || user.getUserRole() == 1 ){
                    //判断用户权限
                    //1：是管理员：就放行
                    filterChain.doFilter(request, response);
                    return;
                }else {
                    //2: 不是管理员则返回餐桌
                    response.sendRedirect(request.getContextPath() + "/front?method=findDinnerTableByStatus");
                    return;
                }
            }
        }
        filterChain.doFilter(request, response);

    }


}
